package com.smartrobot.smartrobot.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.nostra13.universalimageloader.core.ImageLoader;
//import com.readystatesoftware.viewbadger.BadgeView;
import com.smartrobot.smartrobot.Common.CommonFunc;
//import com.smartrobot.smartrobot.DB.NewFriendSqlHelper;
import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.adapter.New_friend_adapter;
import com.smartrobot.smartrobot.adapter.SocialListViewAdapter;
import com.smartrobot.smartrobot.circle.CircleUtil;
import com.smartrobot.smartrobot.circle.NewFriend.NewFriendUtil;
//import com.smartrobot.smartrobot.circle.NewFriend.Notify;
import com.smartrobot.smartrobot.circle.commonData;
import com.smartrobot.smartrobot.circle.searchAndAddFriend;
import com.smartrobot.smartrobot.pagerHolder.SocialCirlePagerHolder;
import com.smartrobot.smartrobot.pojo.NewFriendPojo;
import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.util.ImageLoaderApi;
import com.smartrobot.smartrobot.util.PeopleRegisterMsg;
import com.smartrobot.smartrobot.util.User;
import com.smartrobot.smartrobot.view.ToastCustom;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yeluojun on 2015/1/19.
 */
public class New_friend_activity extends Activity implements View.OnClickListener {
    private static Context context;
    private static ProgressBar new_friend_loading;
    private static Handler handler;
    private final Handler changeHandler = new Handler();
    private static boolean isOperating = false;

    private New_friend_adapter adapter;
    private NewFriendPojo newFriendPojo;
    private List<NewFriendPojo> pojoList;
    private ListView newFriendListView;
    private ImageView back;
    public static  New_friend_activity instance;


    Intent intent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null){
            throw new NullPointerException();
        }
        this.setContentView(R.layout.new_friend_main);

        init();
    }

    private void init (){
        initData();
        initView();
        showNewFriend();

        intent = new Intent();
//        setResult(0,intent);

        instance = this;
    }

    private void initView(){

        newFriendListView = (ListView)findViewById(R.id.new_friend_list);
        new_friend_loading = (ProgressBar)findViewById(R.id.new_friend_loading);
        back = (ImageView)findViewById(R.id.new_friend_back);

        back.setOnClickListener(this);
    }

    private void initData(){

        context = this.getApplicationContext();
        newFriendPojo = new NewFriendPojo();
        pojoList = new ArrayList<NewFriendPojo>();
        handler = new addFriendHandle();

        ImageLoader.getInstance().init(ImageLoaderApi.getImageLoaderConfig(context));


    }


    private void initAdapter(){

        adapter = new New_friend_adapter(context,pojoList);
        newFriendListView.setAdapter(adapter);
    }


    private void showNewFriend(){

        if(User.getInstance()==null){
            User.getUserInfo(context);
        }
        NewFriendUtil newFriendUtil = new NewFriendUtil(context,CommonFunc.stringToMD5(User.getInstance().getId()));
        pojoList = newFriendUtil.getData();

        adapter = new New_friend_adapter(context,pojoList);
        newFriendListView.setAdapter(adapter);

        newFriendUtil.saveNewFriendTip("");

        //隐藏 “new"
        if(SocialListViewAdapter.instance!=null){
            SocialListViewAdapter.instance.new_friend_tip.setVisibility(View.GONE);
        }

        if(MainActivity.instance!=null){
            MainActivity.instance.hideNewSocial();
        }
    }


    /*接受申请*/
    public static void accept(NewFriendPojo newFriendPojo){
        if(!isOperating){
//            isOperating = true;
            addFriendOrCircle(newFriendPojo);
        }

    }

    /*加入社交圈或者是添加好友*/
    public static void addFriendOrCircle(NewFriendPojo newFriendPojo){
        new_friend_loading.setVisibility(View.VISIBLE);
        searchAndAddFriend sf = new searchAndAddFriend();
        sf.setUserId(newFriendPojo.getUserId());
        sf.addFriendOrJoinCircle(handler, context, newFriendPojo);
    }

    /* 添加好友 */
    public void addFriend(NewFriendPojo newFriendPojo){
        new_friend_loading.setVisibility(View.VISIBLE);
        searchAndAddFriend sf = new searchAndAddFriend();
        sf.setUserId(newFriendPojo.getUserId());
        sf.addFriend(handler, context, newFriendPojo);
    }


    /* 加入社交圈 */
    public void joinCircle(NewFriendPojo newFriendPojo){
        new_friend_loading.setVisibility(View.VISIBLE);
        searchAndAddFriend sf = new searchAndAddFriend();
        sf.setUserId(newFriendPojo.getUserId());
        sf.addCircle(handler, context, newFriendPojo);
    }


    /*添加列表*/
    public  void changeOnly(final NewFriendPojo newFriendPojo,final String status){
        Thread t = new Thread(){
            public void run() {
                List<NewFriendPojo> pojo = new ArrayList<NewFriendPojo>();

                if(status.equals("update")){   //更新数据
                    for(int i=0;i<pojoList.size();i++){
                        if( pojoList.get(i).getUserId().equals(newFriendPojo.getUserId())){
                            pojoList.get(i).setMsg(newFriendPojo.getMsg());
                            pojoList.get(i).setStatus(newFriendPojo.getStatus());
                            break;
                        }
                    }
                }else{  //添加数据
                    pojo.add(newFriendPojo);
                    pojo.addAll(pojoList);

                    pojoList.clear();
                    pojoList.addAll(pojo);
                }


                Log.e("=====开始改变=====","！！！！！！");
                changeHandler.post(changeRun);
            }
        };
        t.start();
    }

    /*减少列表*/
    public void removeList(String userId){

        boolean tempT = false;

        for(int i=0;i<pojoList.size();i++){
            if(pojoList.get(i).getUserId().equals(userId)){
                pojoList.remove(i);
                tempT = true;
                break;
            }
        }

        if(tempT){
            changeHandler.post(changeRun);
        }

    }





    final Runnable changeRun = new Runnable() {
        public void run() {
            Log.e("=====改变列表=====","！！！！！！");
            changeNotify();

        }
    };


    /*更改列表*/
    public void changeNotify(){
        adapter.changeNotify();
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){

            case R.id.new_friend_back:

                New_friend_activity.this.finish();

                break;

        }

    }


    /*handler*/
    class addFriendHandle extends Handler {
        @Override
        public void dispatchMessage(Message msg) {


            //添加朋友成功
            if(msg.what== commonData.ADD_FRIEND_SUCCESS_CODE){

                Log.e("====添加好友成功！！！！","");

                changeNotify();

                if(SocialCirlePagerHolder.socialCirlePagerHolder!=null){
                    /*改变朋友圈列表*/
                    SocialCirlePagerHolder.socialCirlePagerHolder.friendAdapterChange();
                }

                new_friend_loading.setVisibility(View.GONE);
                isOperating = false;

                if(SocialListViewAdapter.instance!=null){
                    //提醒更新
                    SocialListViewAdapter.instance.notifyDataSetChanged();
                }else{
                    CircleUtil.isFriendChange = true;
                }

                return;
            }



            //加入社交圈成功
            if(msg.what ==commonData.ADD_CIRCLE_SUCCESS_CODE){
                Log.e("====加入社交圈！！！！","");
                changeNotify();
                new_friend_loading.setVisibility(View.GONE);
                isOperating = false;



                //更新朋友列表
                if(SocialListViewAdapter.instance!=null){
                    //提醒更新
                    SocialListViewAdapter.instance.notifyDataSetChanged();
                }else{
                    CircleUtil.isFriendChange = true;
                }

                return;
            }

            //邀请加入社交圈成功
            if(msg.what ==commonData.INVITE_ADD_CIRCLE_SUCCESS_CODE){
                changeNotify();
                new_friend_loading.setVisibility(View.GONE);
                isOperating = false;


                //更新朋友列表
                if(SocialListViewAdapter.instance!=null){
                    //提醒更新
                    SocialListViewAdapter.instance.notifyDataSetChanged();
                }else{
                    CircleUtil.isFriendChange = true;
                }
                return;
            }


            //用户已经存在社交圈
            if(msg.what ==commonData.USER_CIRCLE_EXIST_CODE){
                try{

                    Map<String,Object>map = (Map)msg.obj;
                    final NewFriendPojo pojo= (NewFriendPojo)map.get("pojo");
                    AlertDialog.Builder builder = new AlertDialog.Builder(New_friend_activity.this);
                    builder.setTitle("温馨提示")
                            .setMessage("您已经存在社交圈，是否退出当前社交圈加入该理发师的社交圈？")
                            .setPositiveButton("是，加入社交圈", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    joinCircle(pojo);
                                }
                            })
                            .setNegativeButton("否，直接添加好友", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    addFriend(pojo);
                                }
                            }).show();
                    new_friend_loading.setVisibility(View.GONE);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                    e.getStackTrace();
                }

            }


            //获取好友列表成功
            if(msg.what == commonData.GET_FRIEND_LIST_SUCCESS_CODE){
                return;
            }

            //用户未登录
            if(msg.what == commonData.USE_NOT_LOGIN_CODE){

                Map<String,Object>map = (Map)msg.obj;
                final NewFriendPojo pojo= (NewFriendPojo)map.get("pojo");

                //帮组用户登录
                int flag = msg.arg1;
                if (User.getInstance() != null&&!User.getInstance().getId().equals("未填写") ) {
                    HttpUtil.apiLoginV2(getApplicationContext(), new PeopleRegisterMsg(User.getInstance().getPhone(), User.getInstance().getPwd()), handler,pojo, flag);


                } else if (User.getUserInfo(getApplicationContext())&&!User.getInstance().getId().equals("未填写")) {
                    HttpUtil.apiLoginV2(getApplicationContext(), new PeopleRegisterMsg(User.getInstance().getPhone(), User.getInstance().getPwd()), handler,pojo, flag);
                } else {
                    ToastCustom.showToast(getApplicationContext(), "请登录！");
                }

                new_friend_loading.setVisibility(View.GONE);
                return;

            }

            //登录成功后
            if(msg.what == HttpUtil.LOGIN_SUCCESS){

                Map<String,Object>map = (Map)msg.obj;
                final NewFriendPojo pojo= (NewFriendPojo)map.get("pojo");

                switch (msg.arg1){

                    case commonData.ADD_FRIEND_OR_CIRCLE_WITHOUT_LOGIN:
                        addFriendOrCircle(pojo);
                        break;

                    case commonData.ADD_CIRCLE_WITHOUT_LOGIN:
                        joinCircle(pojo);
                        break;
                    case commonData.ADD_FRIEND_WITHOUT_LOGIN:
                        addFriend(pojo);
                        break;
                }
            }

            //需要显示提示
            if(msg.what==commonData.SHOW_TIP_CODE){
                ToastCustom.showToast(getApplicationContext(), msg.obj.toString());
                new_friend_loading.setVisibility(View.GONE);
                return;
            }



            //无法连接服务器
            if (msg.what == commonData.CAN_NOT_CONNECT_SERVER_CODE){
                ToastCustom.showToast(getApplicationContext(), msg.obj.toString());
//                add_progressBar.setVisibility(View.GONE);
                return;
            }

            //数据异常
            if(msg.what ==commonData.DATA_ERROR_CODE){
//                ToastCustom.showToast(getApplicationContext(),msg.obj.toString());
                new_friend_loading.setVisibility(View.GONE);
                return;
            }


            //其他情况
            if(msg.what ==commonData.USER_ADD_FRIEND_OR_CIRCLE_OTHER_ERROR_CODE){
//                ToastCustom.showToast(getApplicationContext(),msg.obj.toString());
                new_friend_loading.setVisibility(View.GONE);
                return;
            }

        }
    }





    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            Log.e("fanhui ===========","buck");
            setResult(10, intent);
            this.finish();
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }


}
